package com.liu.auth.service;


import com.google.common.collect.Lists;
import com.liu.auth.feginClient.UserClient;
import com.liu.auth.vo.UserVO;
import com.liu.common.enums.HttpStatus;
import com.liu.common.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service("userDetailServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserClient userClient;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserVO loginUser = userClient.getUserByUserName(username).getData(); //调用fegin获取用户信息
        System.out.println("user信息: "+loginUser.toString());
        if (null ==loginUser) {
            throw new BaseException(HttpStatus.NOT_USER);
        }

//通过用户id 查询对应的权限数据,此处根据需要再补上
//        List<Object> permissionByUserId = tbPermissionSService.getPermissionByUserId(tbUser.getId());
        List<Object> permissionByUserId = Lists.newArrayList("a","b");
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        permissionByUserId.forEach(p -> {
            if (p!=null) {
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(p.toString());
                grantedAuthorities.add(simpleGrantedAuthority);
            }
        });
        return new User(loginUser.getLoginName(), loginUser.getPwd(),grantedAuthorities);

    }
}
